const Student = require("../models/Student");
const Class = require('../models/Class')

const validate = require('validate.js')

exports.addStudent = async function (stuObj) {

    // 验证规则
    const rules = {
        name: {
            presence: true, // 属性必须存在且不为undefined
        }
    }
    // 验证通过 返回undefined stuObj:验证对象
    const res = validate.validate(stuObj, rules)
    console.log(res); // { name: [ "Name can't be blank" ] }

    // const ins = await Student.create(stuObj);
    // return ins.toJSON();
};

exports.deleteStudent = async function (id) {
    return await Student.destroy({
        where: {
            id,
        },
    });
};

exports.updateStudent = async function (id, obj) {
    return await Student.update(obj, {
        where: {
            id,
        },
    });
};

// 
exports.findStudents = async function (offest = 1, limit = 10) {
    const result = await Student.findAll({
        attributes: ["id", "name"],
        include: [Class],
        offest: (offest - 1) * limit,
        limit // 分页查询
    })
    const count = await Student.count()
    return {
        count,
        datas: JSON.stringify(result)
    }
    // 或 Student.findAndCountAll
}

// 关联查询
